import 'package:flutter/material.dart';
import 'package:netstorage/navigator/tab_navigator.dart';
import 'package:netstorage/utils/navigator_utils.dart';
import 'package:netstorage/utils/stringUtils.dart';
import 'package:netstorage/widget/input_widget.dart';
import 'package:netstorage/widget/login_button.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:netstorage/dao/login_dao.dart';

/**
 * 2025年6月21日 12:20:09
 * 登录页面
 */
class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  // 添加焦点控制器
  final FocusNode _usernameFocus = FocusNode();
  final FocusNode _passwordFocus = FocusNode();

  bool loginEnable = false;
  String? username = '';
  String? password = '';

  @override
  Widget build(BuildContext context) {
    /* 由于有屏闪的现象，注释下面代码，采用AI的代码
    return Scaffold(
      resizeToAvoidBottomInset: false,// 防止进入登录页面由调用键盘导致画面抖动
      body: Stack(
        children: [ ..._background(), _content() ],
      )
    );
     */
    return Scaffold(
      body: MediaQuery.removePadding(
          context: context,
          removeBottom: true,// 移除底部系统padding
          child: Stack(children: [..._background(), _content()])
      )
    );
  }

  //#region 背景图片+蒙层
  _background() {
    return [
      Positioned.fill(child: Image.asset('images/login-bg1.jpg',fit: BoxFit.cover)),
      // 为上面一个元素添加蒙层
      Positioned.fill(child: Container(decoration: const BoxDecoration(color: Colors.black54)))
    ];
  }
  //#endregion

  //#region 页面元素
  _content() {
    return Positioned.fill(
      left: 25, right: 25,
      child: ListView(// 可拖拽移位
        children: [
          SizedBox(height: 100),
          const Text('账号密码登录', style: TextStyle(fontSize: 26, color: Colors.white),),
          SizedBox(height: 100),
          // 账号
          InputWidget(
            placeHolder: '请输入登录账号',
            focusNode: _usernameFocus,
            onFieldSubmitted:  (value) { // 添加提交回调
              FocusScope.of(context).requestFocus(_passwordFocus);
            },
            onChanged: (text){
              username = text;
              print('username:$username');
              print('userIsEmpty:${isEmpty(username)}');
              _isBtnEnable();// 设置登录按钮是否可用
            },),

          // 密码
          InputWidget(
            placeHolder: '请输入密码', isPwd: true,
            focusNode: _passwordFocus,
            onFieldSubmitted:  (value) { // 添加提交回调
              if(loginEnable) _login();
            },
            onChanged: (text){
            password = text;
              _isBtnEnable();
            }
          ),
          SizedBox(height: 50),
          // 调用函数几种方式：
          // onPressed: () => _login()
          // onPressed: _login        仅仅是函数名称
          LoginButton('登录', enable: loginEnable, onPressed: () => _login(),),
          SizedBox(height: 25),
          Align(
            alignment: Alignment.centerRight,
            child: InkWell(
              onTap: () => _gotoRegistration(),
              child: const Text('注册账号', style: TextStyle(color: Colors.white))
            ),

          )
        ]
      )
    );
  }
  //#endregion

  //#region 登录按钮是否可用
  void _isBtnEnable(){
    bool enabled = true;
    if(isEmpty(username)) {
      enabled = false;
      print('username是空');
    }
    if(isEmpty(password)) {
      enabled = false;
      print('password是空');
    }
    setState(() {
      loginEnable = enabled;
      print('更新按钮状态为：$loginEnable');
    });
  }
  //#endregion

  //#region 登录
  void _login() async {
    try{
      bool loginSuccess = await LoginDao.login(username: 'test', password: 'test');
      // if(loginSuccess) NavigatorUtils.goHome(context);
      if(loginSuccess) NavigatorUtils.push(context, TabNavigator());
    }catch(e){
      print(e);
    }
  }
  //#endregion

  //#region 跳转到注册页面，app 打开浏览器
  void _gotoRegistration() async {
    Uri uri = Uri.parse('https://api.devio.org/uapi/swagger-ui.html#/Account/registrationUsingPOST');
    if(!await launchUrl(uri, mode: LaunchMode.externalApplication))
      throw 'could not launch $uri';
  }
  //#endregion

  @override
  void dispose() {
    _usernameFocus.dispose();
    _passwordFocus.dispose();
    super.dispose();
  }
}
